package com.jydd.plug_in_study;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

import com.jydd.plug_in_study.util.Util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * created by 韦敏敏
 * on 2019/12/26
 */
public class ProxyInstrumentation extends Instrumentation {
    private Instrumentation mInstrumentation = null;
    public ProxyInstrumentation(Instrumentation instrumentation){
        this.mInstrumentation = instrumentation;
    }
    public ActivityResult executeStartActivity(Context who, IBinder contextThread,IBinder token ,Activity target, Intent intent, int requestCode, Bundle options){
        StringBuilder sb = new StringBuilder();
        sb.append("who = [").append("], ")
                .append("contextThread = [").append(contextThread).append("], ")
                .append("token = [").append(token).append("], ")
                .append("target = [").append(target).append("], ")
                .append("intent = [").append(intent).append("], ")
                .append("requestCode = [").append(requestCode).append("], ")
                .append("options = [").append(options).append("]");
        Util.log("Hook成功，执行了startActivity: " + who);
        Intent replaceIntent = new Intent(target, TextActivity.class);
        replaceIntent.putExtra(TextActivity.TARGET_COMPONENT, intent);
        intent = replaceIntent;
        try {
            Method executeStartActivity = Instrumentation.class.getDeclaredMethod(
                    "execStartActivity",
                    Context.class,
                    IBinder.class,
                    IBinder.class,
                    Activity.class,
                    Intent.class,
                    int.class,
                    Bundle.class);
            return (ActivityResult) executeStartActivity.invoke(mInstrumentation, who, contextThread,token, target, intent, requestCode, options);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

}
